const moment = require('moment')
const { sequelize } = require('../core/db')
const { Sequelize, Model } = require('sequelize')
const User = require('./User')
const Category = require('./Category')
const Like = require('./Like')

class Article extends Model {}

Article.init(
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    title: {
      type: Sequelize.STRING(50),
      allowNull: false,
      comment: '文章标题'
    },
    content: {
      type: Sequelize.TEXT,
      allowNull: false,
      comment: '文章内容'
    },
    html: {
      type: Sequelize.TEXT,
      allowNull: false,
      comment: '文章内容html版'
    },
    cover: {
      type: Sequelize.STRING,
      allowNull: true,
      comment: '文章封面'
    },
    browse: {
      type: Sequelize.INTEGER,
      allowNull: true,
      defaultValue: 0,
      comment: '文章浏览次数'
    },
    status: {
      type: Sequelize.STRING('32'),
      allowNull: false,
      defaultValue: 0,
      comment: '文章状态, 0草稿，1发布, 2禁止发布'
    },
    label: {
      type: Sequelize.STRING(128),
      allowNull: true,
      comment: '标签'
    },
    created_at: {
      type: Sequelize.DATE,
      allowNull: false,
      get() {
        return moment(this.getDataValue('created_at')).format('YYYY-MM-DD HH:mm')
      }
    },
    updated_at: {
      type: Sequelize.DATE,
      allowNull: false,
      get() {
        return moment(this.getDataValue('updated_at')).format('YYYY-MM-DD HH:mm')
      }
    }
  },
  {
    sequelize,
    modelName: 'article',
    tableName: 'articles'
  }
)

Article.belongsTo(User, {
  foreignKey: 'user_id', targetKey: 'id', as: 'user'
})

Article.belongsTo(Category, {
  foreignKey: 'category_id', targetKey: 'id', as: 'category'
})

// Article.hasMany(Like, {
//   foreignKey: 'id', targetKey: 'target_id', as: 'like'
// })

module.exports = Article
